<style>
.tabs .ivu-badge-count{
  background-color: #ffffff !important; color: #007bff !important; font-size: 12px;
}
.custom-paragraph {
  font-size: 12px;
}

.flex-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 10px;
}
.input-container {
  margin-right: 5px;
  width: 220px;
}
</style>
<template>
  <div>
    <div>
      <Tabs  v-if="!loading"  :animated="false"  v-model="activeTab" @on-click="handleTabClick" value="name1" class="tabs">
        <TabPane :label="label1" name="name1">
          <div class="flex-container">
            <Input v-model="keyword" @on-search="searchPort" @on-clear="clearInput" search enter-button placeholder="搜索" clearable class="input-container" />
            <Button   type="primary"  @click="handleButtonClick"  >更新所选</Button>
          </div>
          <Drawer
              title="添加项目"
              v-model="longdao"
              width="700"
              :mask-closable="true"
              :styles="styles"
              ref="drawerName"
              @on-close="handleClose"
          >
            <Form  ref="myForm" :model="formData"  :rules="ruleValidate">
              <div class="custom-paragraph">
                <p>已选数量：{{ selectedQuantity }}个</p>
                <p>已选服务：{{ selectedServices }}</p>
              </div>
              <Row :gutter="32">
                <Col span="12">
                  <FormItem label="是否存在" label-position="top" prop="IsExists">
                    <Select   v-model="formData.IsExists" >
                      <Option value="存在">存在</Option>
                      <Option value="不存在">不存在</Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem label="是否修复" label-position="top" prop="IsRepaired">
                    <Select   v-model="formData.IsRepaired" :disabled="formData.IsExists === '不存在'">
                      <Option value="未修复">未修复</Option>
                      <Option value="已修复">已修复</Option>
                    </Select>
                  </FormItem>
                </Col>
              </Row>
            </Form>
            <div class="demo-drawer-footer">
              <Button style="margin-right: 8px" @click="longdao = false;" >取消</Button>
              <Button type="primary" @click="saveServiceData">确定</Button>
            </div>
          </Drawer>
          <Table  :loading="loading"  border  :columns="columns" :data="data"  @on-selection-change="handleSelect"></Table>
          <Page
              style="margin-top: 10px;text-align: center"
              show-total
              show-sizer
              :total="total"
              :page-size="pageSize"
              :current="currentPage"
              @on-page-size-change="handlePageSizeChange"
              @on-change="handlePageChange"
          ></Page>
        </TabPane>
        <TabPane :label="label2" name="name2">
          <Table border :columns="columns" :data="data"></Table>
          <Page
              style="margin-top: 10px;text-align: center"
              show-total
              show-sizer
              :total="repTotal"
              :page-size="pageSize"
              :current="currentPage"
              @on-page-size-change="handlePageSizeChange"
              @on-change="handlePageChange"
          ></Page>
        </TabPane>
        <TabPane :label="label3" name="name3">
          <Table border :columns="columns" :data="data"></Table>
          <Page
              style="margin-top: 10px;text-align: center"
              show-total
              show-sizer
              :total="unrepTotal"
              :page-size="pageSize"
              :current="currentPage"
              @on-page-size-change="handlePageSizeChange"
              @on-change="handlePageChange"
          ></Page>
        </TabPane>
      </Tabs>
    </div>
  </div>
</template>
<script>
import axios from "axios";


export default {
  name:'VulnerabilityStaus',
  inject: ['reload'],
  data () {
    return {
      label1: (h) => {
        return h('span', [
          h('span', '全部'),
          h('Badge', {
            props: {
              count: this.allCount,
              overflowCount: 10000000
            },
          })
        ])
      },
      label2: (h) => {
        return h('span', [
          h('span', '已修复'),
          h('Badge', {
            class: 'custom-badge',
            props: {
              count: this.repTotal,
              overflowCount: 10000000
            },
          })
        ])
      },
      label3: (h) => {
        return h('span', [
          h('span', '未修复'),
          h('Badge', {
            props: {
              count: this.unrepTotal,
              overflowCount: 10000000
            },
          })
        ])
      },
      longdao: false, //控制抽屉的显示和隐藏
      styles: {
        height: 'calc(100% - 55px)',
        overflow: 'auto',
        paddingBottom: '53px',
        position: 'static'
      },
      formData: {
        IsExists: '',
        IsRepaired: '',
        Sname:'',
        selectid:'',
      },
      ruleValidate: {
        IsExists: [{required: true, message: '请选择其中一项', trigger: 'blur'}],
        IsRepaired: [{required: true, message: '请选择其中一项', trigger: 'blur'}],
      },
      data: [],
      repdata:[],
      unrepdata:[],
      loading: false,
      currentPage: 1, // 当前页码
      pageSize: 10,
      total :0,
      repTotal:  0,
      unrepTotal: 0,
      allCount:0,
      keyword: '',
      selectedQuantity: 0, // 服务数量
      selectedServices: '', // 服务名称
      selectid:[],
      activeTab: this.$route.query.tab, // 设置默认的选项卡
      company: this.$route.query.company, // 获取company参数
      ability:this.$route.query.ability,// 获取ability参数

      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '漏洞名称',
          align: 'center',
          key: 'vname',
        },
        {
          title: '服务名称',
          align: 'center',
          key: 'sname'
        },
        {
          title: '研发人员',
          align: "center",
          key: 'develop'
        },
        {
          title: '是否存在',
          align: 'center',
          key: 'exists'
        },
        {
          title: '是否修复',
          align: 'center',
          key: 'repaird',
        },
        {
          title: '修复完成时间',
          align: 'center',
          key: 'expected'
        }
      ],
    }
  },
  watch: {
    'formData.IsExists': function(newVal) {
      if (newVal === '不存在') {
        this.formData.IsRepaired = '已修复';
      }
    }
  },
  mounted() {
    this.getvulnerabilityData();
  },
  methods: {
    background(type) {
      this.$Message[type]({
        background: true,
        content: type === 'success' ? '编辑成功' : '编辑失败'
      });
    },
    handleButtonClick() {
      this.longdao = true;
      if ( this.selectedQuantity > 0) {
        this.longdao = true;
      }else{
        this.longdao = false;
        this.$Message.error('请先选择要更新的项目'); // 弹出提示信息
      }
    },
    //关闭抽屉
    handleClose() {
      this.formData = {}; // 清空表单数据
      this.selectedQuantity = 0;  //清空服务数量
      this.selectedServices =''; //清空服务名称
      this.data.forEach(item => {
        this.$set(item, 'selected', false); // 取消选择
        this.$set(item, 'isSingleSelection', false);
      });
      this.data = JSON.parse(JSON.stringify(this.data));
    },
    handleSelect(selection) {
      this.selectid = selection.map(item => item.id).join(', ');
      this.selectedQuantity = selection.length;
      this.selectedServices = selection.map(item => item.sname).join(', ');
    },
    handleTabClick(tab) {
      this.pageSize = 10
      this.activeTab = tab;// 点击选项卡时更新当前的选项卡
      this.$router.push(`/dashboard/projectlist/vulnerability?ability=${this.ability}&company=${this.company}&tab=${tab}`);
      this.currentPage = 1
      this.getvulnerabilityData()
    },
    handlePageSizeChange(pageSize) {
      this.pageSize = pageSize;
      // 执行其他操作，比如重新加载数据
      this.getvulnerabilityData();
    },
    handlePageChange(currentPage) {
      // 当页码变化时，更新currentPage并重新获取表格数据
      this.currentPage = currentPage;
      this.getvulnerabilityData();
    },
    clearInput() {
      this.keyword = ''; // 清空关键字
      this.getvulnerabilityData(); // 重新获取数据
    },
    searchPort() {
      this.currentPage = 1
      this.getvulnerabilityData();
    },
    saveServiceData() {
      this.formData.Sname=this.selectedServices
      this.formData.selectid = this.selectid
      this.$refs['myForm'].validate((valid) => {
        if (valid) {
          axios.post(`http://172.30.53.223:8888/api/editvulnerability?company=${this.company}&ability=${this.ability}`, this.formData)
              .then(() => {
                // 数据保存成
                this.background('success');
                this.longdao = false;
                this.$refs.myForm.resetFields();
                this.searchPort()
              })
              .catch(error => {
                // 处理错误
                console.error(error);
                this.background('error');
              });
        } else {
          // 表单验证不通过的逻辑
          return; // 阻止提交操作
        }
      });
    },
    getvulnerabilityData() {
      this.loading = true; // 设置 loading 为 true，显示加载状态
      axios.get(`http://172.30.53.223:8888/api/getlist?ability=${this.ability}&company=${this.company}&page=${this.currentPage}&pageSize=${this.pageSize}&keyword=${this.keyword}&requestType=${this.$route.query.tab}`)
          .then(response => {
            if (response.data.list === null) {
              this.data = [];
            } else {
              this.data = response.data.list.map(list => ({
                id: list.ID,
                vname: list.Vname,
                sname: list.ServerID,
                develop: list.Develop,
                exists: list.Exists,
                repaird: list.Repaird,
                expected: list.Expected,
              }));
            }
            this.total = response.data.total;
            this.loading = false; // 数据加载完成后，设置 loading 为 false，取消加载状态
            this.repTotal =response.data.repairedCount;
            this.unrepTotal = response.data.unrepairedCount;
            this.allCount = response.data.allCount;
          })
          .catch(error => {
            console.error('Error fetching vulnerability data:', error);
            this.loading = false; // 出错时也要设置 loading 为 false，取消加载状态
          });
    },
  }
}
</script>
<style>
.demo-drawer-footer{
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;

}
</style>